//
//  UIViewController+AOP.m
//  myfamily
//
//  Created by xiayiyong on 15/8/7.
//  Copyright (c) 2015年 我爱我家. All rights reserved.
//

#import "UIViewController+AOP.h"
#import <objc/runtime.h>

@implementation UIViewController (AOP)


+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originalMethod = class_getInstanceMethod([self class], @selector(viewDidLoad));
        Method swizzledMethod = class_getInstanceMethod([self class], @selector(swizzled_viewDidLoad));
        //运行时函数class_addMethod 如果发现方法已经存在，会失败返回
        BOOL didAddMethod = class_addMethod([self class], @selector(viewDidLoad), method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (didAddMethod) {
            //如果添加成功，再把目标类中的方法替换为旧有的实现:
            class_replaceMethod([self class], @selector(swizzled_viewDidLoad), method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

- (void)swizzled_viewDidLoad {
    // 调用旧的实现。因为它们已经被替换了
    [self swizzled_viewDidLoad];
    if ([self isKindOfClass:NSClassFromString(@"LoginViewController")])
    {
        self.view.backgroundColor = [UIColor blueColor];
    }
    
    if ([self isKindOfClass:NSClassFromString(@"BaseTableViewController")])
    {
        self.view.backgroundColor = [UIColor redColor];
    }
    
}

@end
